import React from 'react';
import { Breadcrumb, Avatar, Dropdown, Menu, Layout } from 'antd';
import { LogoutOutlined, SettingOutlined, MenuUnfoldOutlined, MenuFoldOutlined } from '@ant-design/icons';
import { useLocation, useHistory } from 'react-router-dom';
import { Token, getUserData } from '../utils/const.ts';
import { MenuData } from '../menuData.js';
import './Header.css';

const { Header: AntHeader } = Layout;

function getBreadcrumbItems(pathname) {
  // 递归查找路径对应的 label
  const items = [];
  function findInMenu(menu, path) {
    for (const item of menu) {
      if (item.children) {
        const found = findInMenu(item.children, path);
        if (found) {
          items.unshift({ path: item.key, title: item.label });
          return found;
        }
      }
      if (item.key === path) {
        items.push({ path: item.key, title: item.label });
        return true;
      }
    }
    return false;
  }
  findInMenu(MenuData, pathname);
  return items;
}

const Header = ({ collapsed, onToggle }) => {
  const location = useLocation();
  const history = useHistory();
  const breadcrumbItems = getBreadcrumbItems(location.pathname);

  const handleMenuClick = ({ key }) => {
    if (key === 'profile') {
      // 跳转到个人资料页（假设为 /profile）
      history.push('/profile');
    } else if (key === 'logout') {
      // 清除 token 和登录信息
      localStorage.removeItem(Token);
      localStorage.removeItem('loginRes');
      history.push('/login');
    }
  };

  const menu = (
    <Menu onClick={handleMenuClick}>
      <Menu.Item key="profile" icon={<SettingOutlined />}>
        个人资料
      </Menu.Item>
      <Menu.Item key="logout" icon={<LogoutOutlined />}>
        退出登录
      </Menu.Item>
    </Menu>
  );

  return (
    <AntHeader className="app-header">
      <div className="header-left">
        <span className="menu-toggle" onClick={onToggle}>
          {collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
        </span>
        <Breadcrumb className="breadcrumb">
          {breadcrumbItems.map(item => (
            <Breadcrumb.Item key={item.path}>{item.title}</Breadcrumb.Item>
          ))}
        </Breadcrumb>
      </div>
      <Dropdown overlay={menu} placement="bottomRight">
        <Avatar 
          size="small" 
          src={JSON.parse(getUserData())?.pic} 
          className="user-avatar" 
        />
      </Dropdown>
    </AntHeader>
  );
};

export default Header; 